package mysql

import (
	"api/appconfig"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var (
	Db  *gorm.DB
	err error
)

func InitMysql() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	mysqlConf := appconfig.AppConf.MySQlConfig
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlConf.User, mysqlConf.Password, mysqlConf.Host, mysqlConf.Port, mysqlConf.Database)
	Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		fmt.Println("数据库连接信息失败", err)
		return
	}
	fmt.Println("数据库连接信息成功")
	err = Db.Debug().AutoMigrate(&Users{}, &Goods{}, &Carts{})
	if err != nil {
		fmt.Println("数据库迁移信息失败", err)
		return
	}
	fmt.Println("数据库迁移信息成功")
}
